package com.bw.mallshop.mvvm.viewmodel;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.blankj.utilcode.util.LogUtils;
import com.bw.common.BaseApplication;
import com.bw.common.entity.BaseEntity;
import com.bw.common.mvvm.viewmodel.BaseViewModel;
import com.bw.mallshop.App;
import com.bw.mallshop.R;
import com.bw.mallshop.adapter.CarListAdapter;
import com.bw.mallshop.annotation.CheckLogin;
import com.bw.mallshop.dao.UserSingle;
import com.bw.mallshop.entity.AddCarEntity;
import com.bw.mallshop.entity.CarListEntity;
import com.bw.mallshop.entity.DelCarEntity;
import com.bw.mallshop.entity.DelLocalCarEntity;
import com.bw.mallshop.entity.SubCarEntity;
import com.bw.mallshop.mvvm.model.CarListModel;
import com.bw.mallshop.mvvm.view.ConfirmOrderActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class CarListViewModel extends BaseViewModel<CarListModel> implements OnItemClickListener, OnItemChildClickListener {

    public ObservableField<String>edtStr = new ObservableField<>("编辑");
    public ObservableField<Boolean>allCheck = new ObservableField<>(true);
    public ObservableField<String>allPrice = new ObservableField<>("￥0");
    public ObservableField<String>payTxt = new ObservableField<>("去结算");
    private List<CarListEntity.Values>list = new ArrayList<>();//去结算进入编辑时得原始数据
    private List<Integer>delIndex = new ArrayList<>();
    private float price = 0f;
    public CarListAdapter adapter = new CarListAdapter();
    public int mergeNum = 0;
    public int type = 0;

    @Override
    protected void initData() {
        adapter.setOnItemChildClickListener(this);
        adapter.setOnItemClickListener(this);
        //获取离线购物车数据
        m.selCarDao().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    //同步购物车数据逻辑->拉取服务器最新对应用户购物车数据->离线购物车数据与服务器购物车数据比较
    //去重离线购物车与在线购物车相同数据,提交离线购物车数据,拉取最新购物车数据
    //当用户登录后在进入购物车界面同步逻辑失效
    //每次进入购物列表界面:先查询本地离线购物车数据,查询完成后，无论是否具有离线购物车数据
    //获取服务器用户购物车数据;具有本地数据以及在线数据->同步
    public void uploadCarList(){
        //获取在线购物车列表数据
        Map<String,Object>map = new HashMap<>();
        map.put("id",UserSingle.getInstance().userEntityValues.id);
        m.requestCarList(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    protected void result(BaseEntity entity) {
        if (entity instanceof CarListEntity){
            CarListEntity carListEntity = (CarListEntity) entity;
            if (carListEntity.message.equals("获取成功")){
                //获取到得离线数据源
                if (carListEntity.data.size()>0) {
                    adapter.setNewInstance(carListEntity.data);
                    totalPrice();
                }
                //强制获取在线购物车数据
                if (!UserSingle.getInstance().isLogin())
                    return;
                Map<String,Object>map = new HashMap<>();
                map.put("id",UserSingle.getInstance().userEntityValues.id);
                m.requestCarList(map).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(this);
            }else {
                //获取到服务器在线数据源
                //用户未登录，获取离线数据源，登录获取在线数据源
                //区分adapter中是否包含数据源,且数据源imie是否为空
                if (adapter.getData().size()>0
                        &&!TextUtils.isEmpty(adapter.getItem(0).imie)){
                    //具有离线数据源->同步合并数据源
                    list = adapter.getData();
                    //清除原有数据统计金额以及适配器上数据
                    adapter.setNewInstance(new ArrayList<>());
                    totalPrice();
                    //比较数据并且进行提交操作
                    List<CarListEntity.Values>onlineList = carListEntity.data;
                    //循环遍历在线数据源
                    if(onlineList !=null) {
                        for (CarListEntity.Values onlineEntity : onlineList) {
                            //循环遍历本地数据源
                            for (int i = list.size() - 1; i >= 0; i--) {
                                if (list.get(i).goods_id == onlineEntity.goods_id)
                                    list.remove(i);
                            }
                        }
                    }
                    //添加购物车操作
                    if (list.size()==0) {
                        adapter.setNewInstance(carListEntity.data);
                        totalPrice();
                        return;
                    }
                    Map<String,Object>[]parames = new HashMap[list.size()];
                    for (int i = 0;i < list.size();i ++){
                        parames[i]=new HashMap<>();
                        parames[i].put("goodsCount","1");
                        parames[i].put("goodsDesc",list.get(i).goods_desc);
                        parames[i].put("goodsIcon",list.get(i).goods_icon);
                        parames[i].put("goodsId",list.get(i).goods_id);
                        parames[i].put("goodsPrice",list.get(i).goods_price);
                        parames[i].put("goodsSku",list.get(i).goods_sku);
                        parames[i].put("time",System.currentTimeMillis()/1000);
                        parames[i].put("userId",UserSingle.getInstance().userEntityValues.id);
                    }
                    m.addAllCar(parames).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(this);
                    return;
                }
                adapter.setNewInstance(carListEntity.data);
                totalPrice();
                //删除本地购物车数据
                m.delCarList().subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(this);
            }
        }else if (entity instanceof DelCarEntity){
            if (entity.message.equals("删除购物车成功")){
                //移除列表中对应数据
                List<CarListEntity.Values> newList = new ArrayList<>();
                for (CarListEntity.Values values : adapter.getData()){
                    boolean flag = true;
                    for (Integer integer : delIndex){
                        if (values.id==integer){
                            flag = false;
                        }
                    }
                    if (flag)
                        newList.add(values);
                }
                adapter.setNewInstance(newList);
            }
        }else if (entity instanceof AddCarEntity){
            //拉取最新数据->原始数据清零
            mergeNum +=1;
        }else if (entity instanceof DelLocalCarEntity){
            LogUtils.e("清空本地数据");
        }else if (entity instanceof SubCarEntity){
            SubCarEntity subCarEntity = (SubCarEntity) entity;
            if (subCarEntity.message.equals("购物车提交成功")){
                //跳转确认订单界面->订单信息;收货地址;提交购物车返回订单id
                int orderId = subCarEntity.data;
                ArrayList<CarListEntity.Values>listEntities = new ArrayList<>();
                for (CarListEntity.Values values : list){
                    if (values.selFlag) {
                        listEntities.add(values);
                    }
                }
                Bundle bundle = new Bundle();
                bundle.putInt("orderId",orderId);
                bundle.putSerializable("goodsList",listEntities);
                startPage(ConfirmOrderActivity.class,bundle);
                return;
            }
            showErro(subCarEntity.message);
        }
    }

    @Override
    public void onComplete() {
        super.onComplete();
        if (list.size() == mergeNum&&list.size()>0){
            //离线数据同步完成,刷新购物车列表数据
            adapter.setNewInstance(new ArrayList<>());
            totalPrice();
            //清除本地记录数据
            list.clear();
            mergeNum = 0;
            Map<String,Object>map = new HashMap<>();
            map.put("id",UserSingle.getInstance().userEntityValues.id);
            m.requestCarList(map).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }
    }

    //编辑监听器
    public void edtClickListener(){
        if (edtStr.get().equals("编辑")){
            edtStr.set("完成");
            payTxt.set("删除");
            allCheck.set(false);
            allPrice.set("");
            for (int i = 0;i < adapter.getData().size();i ++){
                CarListEntity.Values values = new  CarListEntity.Values();
                values.id = adapter.getItem(i).id;
                values.selFlag = adapter.getItem(i).selFlag;
                values.goods_count = adapter.getItem(i).goods_count;
                values.goods_desc = adapter.getItem(i).goods_desc;
                values.goods_icon = adapter.getItem(i).goods_icon;
                values.goods_id = adapter.getItem(i).goods_id;
                values.goods_price = adapter.getItem(i).goods_price;
                values.goods_sku = adapter.getItem(i).goods_sku;
                values.user_id = adapter.getItem(i).user_id;
                list.add(values);
            }
            List<CarListEntity.Values>edtList = new ArrayList<>();
            edtList.addAll(adapter.getData());
            for (int i=0;i < edtList.size();i ++){
                edtList.get(i).selFlag = false;
            }
            adapter.setNewInstance(edtList);
        }else {
            edtStr.set("编辑");
            payTxt.set("去结算");
            List<CarListEntity.Values>newList = new ArrayList<>();
            List<CarListEntity.Values>edtList = adapter.getData();
            for (CarListEntity.Values values : list){
                for (CarListEntity.Values entity : edtList){
                    if (values.id == entity.id){
                        newList.add(values);
                    }
                }
            }
            adapter.setNewInstance(newList);
            //设置底部是否全选以及设置总金额
            allCheck.set(isAllChecked());
            totalPrice();
        }
    }

    //删除方法
    private void del(){
        //获取要删除数据
        List<CarListEntity.Values>list = adapter.getData();
        for (int i = 0;i < list.size();i ++){
            CarListEntity.Values values = list.get(i);
            if (values.selFlag) {
                delIndex.add(values.id);
            }
        }
        Map<String,Object>map = new HashMap<>();
        map.put("cartIdList",delIndex);
        m.requestDel(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    //提交监听方法
    public void subCar(){
        if (payTxt.get().equals("去结算")){
            subCarList();
        }else {
            //删除
            del();
        }
    }

    //提交
    @CheckLogin
    private void subCarList(){
        /**
         *
         "goodsList": [
         {
         "goods_count": 0,
         "goods_desc": "string",
         "goods_icon": "string",
         "goods_id": 0,
         "goods_price": "string",
         "goods_sku": "string",
         "id": 0,
         "order_id": 0
         }
         ],
         "totalPrice": 0,
         "userId": 0
         }
         * */
        list.clear();
        list = adapter.getData();
        Map<String,Object>map=new HashMap<>();
        map.put("userId",UserSingle.getInstance().userEntityValues.id);
        map.put("totalPrice",price);
        List<CarListEntity.Values>listEntities = new ArrayList<>();
        for (CarListEntity.Values values : list){
            if (values.selFlag) {
                listEntities.add(values);
            }
        }
        map.put("goodsList",listEntities);
        m.requstSubCar(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    //全选监听
    public void checkAllListener(){
        //根据原有选中状态切换为全选/全不选
        boolean checkFlag = isAllChecked();
        for (int i = 0;i <  adapter.getData().size();i ++){
            adapter.getData().get(i).selFlag = !checkFlag;
        }
        adapter.notifyDataSetChanged();
        allCheck.set(!checkFlag);
        totalPrice();
    }

    //判断全选状态方法
    public boolean isAllChecked(){
        List<CarListEntity.Values>list = adapter.getData();
        boolean flag = true;
        for (CarListEntity.Values values : list){
            if (!values.selFlag) {
                flag = false;
                return flag;
            }
        }
        return true;
    }

    public void totalPrice(){
        price = 0f;
        List<CarListEntity.Values>list = adapter.getData();
        for (CarListEntity.Values values : list){
            if (values.selFlag) {
                price = price + values.goods_count*Float.valueOf(values.goods_price);
            }
        }
        allPrice.set("￥"+price);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        //区分点击得控件
        if (view.getId() == R.id.car_item_left){
            int count = this.adapter.getItem(position).goods_count;
            count-=1;
            if (count<1)
                count = 1;
            this.adapter.getItem(position).goods_count = count;
        }else if (view.getId() == R.id.car_item_right){
            int count = this.adapter.getItem(position).goods_count;
            count +=1;
            this.adapter.getItem(position).goods_count = count;
        }else if (view.getId() == R.id.car_item_radio){
            //单选
            this.adapter.getItem(position).selFlag = !this.adapter.getItem(position).selFlag;
            //根据单选状态联动全选状态
            allCheck.set(isAllChecked());
        }
        this.adapter.notifyDataSetChanged();
        totalPrice();
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

    }

}
